package jmine.tec.rpc.integration.server;

import jmine.tec.rpc.integration.api.MockEntityRest;
import jmine.tec.rpc.integration.api.rs.AssociatedMockEntityRS;
import jmine.tec.rpc.integration.api.rs.MockEntityRS;
import jmine.tec.rpc.integration.domain.AssociatedMockEntity;
import jmine.tec.rpc.integration.domain.MockEntity;
import jmine.tec.rpc.server.base.BaseEntityRestService;
import bancosys.tec.persist.dao.BaseDAO;

/**
 * Implementor de MockEntityRestService
 * 
 * @author lundberg
 */
public class MockEntityRestImplementor extends BaseEntityRestService<MockEntityRS, jmine.tec.rpc.integration.domain.MockEntity>
        implements MockEntityRest {

    /**
     * Construtor
     */
    public MockEntityRestImplementor() {
        super(MockEntityRS.class, jmine.tec.rpc.integration.domain.MockEntity.class);
    }

    /**
     * {@inheritDoc}
     */
    public void save(MockEntityRS representation) {
        MockEntity entity = this.getDAO().createBean();
        entity.setValue(representation.getValue());
        for (AssociatedMockEntityRS associatedRepresentation : representation.getReferences()) {
            entity.getReferences().add(this.createAssociatedEntity(entity, associatedRepresentation));
        }
        entity.getPersister().save();
    }

    /**
     * Cria a entidade associada a partir da representação
     * 
     * @param entity entity
     * @param associatedRepresentation associatedRepresentation
     * @return associated entity
     */
    private AssociatedMockEntity createAssociatedEntity(MockEntity entity, AssociatedMockEntityRS associatedRepresentation) {
        BaseDAO<AssociatedMockEntity> dao = this.getDAOFactory().getGenericDAO(AssociatedMockEntity.class);
        AssociatedMockEntity associated = dao.createBean();
        associated.setValue(associatedRepresentation.getValue());
        associated.setMock(entity);
        return associated;
    }
}
